import React, { PureComponent, Suspense } from 'react';
import { Layout, Row, Col, Avatar, Icon, Menu, Badge, Modal, Divider, Tooltip, Spin, notification } from 'antd';
import classNames from 'classnames';
import Link from 'umi/link';
import router from 'umi/router';
import styles from './index.less';
import PageLoading from '../PageLoading';
import HeaderDropdown from '../HeaderDropdown';
import { getDefaultCollapsedSubMenus } from './SiderMenuUtils';
import { title } from '../../defaultSettings';
import request from '@/utils/request';
import ReconnectingWebSocket from 'reconnecting-websocket';
import { getConst } from '@/utils/utils';
import PublicUtils from "@/utils/publicUtils";

const BaseMenu = React.lazy(() => import('./BaseMenu'));
const { Sider } = Layout;
const { confirm } = Modal;

let firstMount = true;

export default class SiderMenu extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      openKeys: getDefaultCollapsedSubMenus(props),
      userInfo: !window.localStorage.getItem('userInfo')
        ? {}
        : JSON.parse(window.localStorage.getItem('userInfo')), //当前登录人信息
      current: '',
      totalCount: {
        newCount: 0,
        noticeCount: 0,
        taskCont: 0,
        approvalCount: 0
      },
      loading: true
    };
  }

  componentDidMount() {
    firstMount = false;
    let _this = this;
    // this.getTaskCount();
    setTimeout(() => {
      this.setState({ loading: false });
    }, 1800);
  }

  static getDerivedStateFromProps(props, state) {
    const { pathname, flatMenuKeysLen } = state;
    if (props.location.pathname !== pathname || props.flatMenuKeys.length !== flatMenuKeysLen) {
      return {
        pathname: props.location.pathname,
        flatMenuKeysLen: props.flatMenuKeys.length,
        openKeys: getDefaultCollapsedSubMenus(props)
      };
    }
    return null;
  }

  isMainMenu = key => {
    const { menuData } = this.props;
    return menuData.some(item => {
      if (key) {
        return item.key === key || item.path === key;
      }
      return false;
    });
  };

  // 获取消息总数
  // getTaskCount = () => {
  //   request
  //     .get('/staff/task/taskCount', {
  //       headers: {
  //         perms: '/dashboard'
  //       }
  //     })
  //     .then(res => {
  //       if (res && res.error_code === 200) {
  //         const totalCount = !res.data
  //           ? {
  //             newCount: 0,
  //             noticeCount: 0,
  //             taskCont: 0,
  //             approvalCount: 0
  //           }
  //           : res.data;

  //         this.setState({ totalCount });
  //       }
  //     });
  // };

  handleOpenChange = openKeys => {
    const moreThanOne = openKeys.filter(openKey => this.isMainMenu(openKey)).length > 1;
    this.setState({
      openKeys: moreThanOne ? [openKeys.pop()] : [...openKeys]
    });
  };

  handleMenuClick = ({ key }) => {
    const { dispatch } = this.props;
    this.setState({
      current: key
    });

    // 异常
    if (key === 'triggerError') {
      router.push('/exception/trigger');
      return;
    }
    // 个人信息
    if (key === 'userInfo') {
      router.push('/personalInfo');
      return;
    }
    // 我的设备
    if (key === 'equipment') {
      router.push('/equipment');
      return;
    }
    // 个人设置
    if (key === 'userCenter') {
      router.push('/account');
      return;
    }
    // 退出登录
    if (key === 'logout') {
      confirm({
        title: '退出系统确认',
        content: '确定要退出登录吗？',
        okText: '确定',
        cancelText: '取消',
        centered: true,
        async onOk() {
          // window.localStorage.removeItem('x-token');
          // window.localStorage.removeItem('userInfo');
          // window.localStorage.removeItem('authorized');
          // router.push('/user/login');
          // dispatch({
          //   type: 'login/logout'
          // });
          let { data, msg, code } = await dispatch({
            type: 'login/logOutApi'
          })
          if (code == 200) {
            window.localStorage.removeItem('x-token');
            window.localStorage.removeItem('userInfo');
            window.localStorage.removeItem('authorized');
            router.push('/user/login');
            dispatch({
              type: 'login/logout'
            });
          } else {
            notification.error({ message: msg ? msg : '请求错误' });
          }
        }
      });
    }
  };

  // 列表跳转，消息
  goToList = url => {
    router.push(url);
  };

  goToFeedBack = () => {
    router.push('/feedBack');
  };

  render() {
    const { logo, collapsed, onCollapse, fixSiderbar, theme, isMobile } = this.props;
    const { openKeys, userInfo, totalCount, loading } = this.state;
    const defaultProps = collapsed ? {} : { openKeys };

    const siderClassName = classNames(styles.sider, {
      [styles.fixSiderBar]: fixSiderbar,
      [styles.light]: theme === 'light'
    });

    const overflowStyle = {
      overflow: 'hidden',
      whiteSpace: 'nowrap',
      textOverflow: 'ellipsis',
      wordBreak: 'break-all'
    };

    const menu = (
      <Menu
        theme="dark"
        className={styles.menu}
        onClick={this.handleMenuClick}
        style={{
          background:
            'linear-gradient(180deg, rgba(24, 126, 244, 1) 0%, rgba(24, 126, 244, 1) 0%, rgba(102, 41, 238, 1) 100%, rgba(102, 41, 238, 1) 100%)'
        }}
      >
        {PublicUtils.checkAuth('2020346_PERMS') && <Menu.Item key="userInfo">
          <Icon type="user" />
          个人信息
        </Menu.Item>}
        {PublicUtils.checkAuth('2020347_PERMS') && <Menu.Divider style={{ backgroundColor: 'rgb(51,153,255)' }} />}
        {PublicUtils.checkAuth('2020347_PERMS') && <Menu.Item key="equipment">
          <Icon type="laptop" />
          我的设备
        </Menu.Item>}
        {PublicUtils.checkAuth('2020348_PERMS') && <Menu.Divider style={{ backgroundColor: 'rgb(51,153,255)' }} />}
        {PublicUtils.checkAuth('2020348_PERMS') && <Menu.Item key="userCenter">
          <Icon type="setting" />
          个人设置
        </Menu.Item>}
        <Menu.Divider style={{ backgroundColor: 'rgb(51,153,255)' }} />
        <Menu.Item key="logout">
          <Icon type="logout" />
          退出系统
        </Menu.Item>
      </Menu>
    );
    return (
      <Sider
        trigger={null}
        collapsible
        collapsed={collapsed}
        breakpoint="md"
        onCollapse={collapse => {
          if (firstMount || !isMobile) {
            onCollapse(collapse);
          }
        }}
        width={202}
        theme={theme}
        className={siderClassName}
      >
        <div className={styles.logo} id="logo">
          <Link to="/">
            <img src={logo} alt="logo" />
          </Link>
        </div>
        <Suspense fallback={<PageLoading />}>
          <HeaderDropdown overlay={menu}>
            <Row
              type="flex"
              justify="space-between"
              align="middle"
              gutter={8}
              style={{ margin: 0, padding: '14px 10px', background: '#1c4cc3', color: '#fff' }}
            >
              <Col span={6}>
                {!userInfo.sysUserHead ? (
                  <Avatar icon="user" size={40} />
                ) : (
                  <Avatar src={userInfo.sysUserHead} size={40} />
                )}
              </Col>
              <Col span={15}>
                <div
                  style={{ fontSize: 16, ...overflowStyle }}
                  title={userInfo.nickName || userInfo.staffName}
                >
                  {userInfo.nickName || userInfo.staffName}
                </div>
                <div
                  style={{ marginTop: 10, color: '#C9C9C9', ...overflowStyle }}
                  title={userInfo.deptName + '-' + userInfo.staffJobName}
                >
                  {userInfo.deptName}-{userInfo.staffJobName}
                </div>
              </Col>
              <Col span={3}>
                <Icon type="down-square" size={40} />
              </Col>
            </Row>
          </HeaderDropdown>
          <div style={{ width: '100%', height: 1, background: 'rgb(51,153,255)' }}></div>
          <BaseMenu
            {...this.props}
            mode="inline"
            handleOpenChange={this.handleOpenChange}
            onOpenChange={this.handleOpenChange}
            style={{ padding: '16px 0 100px', width: '100%' }}
            {...defaultProps}
          />
        </Suspense>
      </Sider>
    );
  }
}
